<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>走进Django | 如是的学习博客</title><meta name="keywords" content="django"><meta name="author" content="rushiy"><meta name="copyright" content="rushiy"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Django是什么Django是一个由Python编写的一个开放源代码的Web应用框架。Python加Django是快速开发、设计、部署网站的最佳组合。 使用Django，只要很少的代码，Python的程序开发人员就可以轻松地完成一个正式网站所需要的大部分内容，并进一步开发出全功能的Web服务Django本身基于MVC模型，即Model（模型）+View（视图）+ Controller（控制器）设">
<meta property="og:type" content="article">
<meta property="og:title" content="走进Django">
<meta property="og:url" content="https://rushiy.gitee.io/django/%E8%B5%B0%E8%BF%9BDjango/index.html">
<meta property="og:site_name" content="如是的学习博客">
<meta property="og:description" content="Django是什么Django是一个由Python编写的一个开放源代码的Web应用框架。Python加Django是快速开发、设计、部署网站的最佳组合。 使用Django，只要很少的代码，Python的程序开发人员就可以轻松地完成一个正式网站所需要的大部分内容，并进一步开发出全功能的Web服务Django本身基于MVC模型，即Model（模型）+View（视图）+ Controller（控制器）设">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-11-01T07:01:20.000Z">
<meta property="article:author" content="rushiy">
<meta property="article:tag" content="django">
<meta name="twitter:card" content="summary"><link rel="shortcut icon" href="/img/favicon.jpg"><link rel="canonical" href="https://rushiy.gitee.io/django/%E8%B5%B0%E8%BF%9BDjango/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '走进Django',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-11-19 01:18:40'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/favicon.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">28</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">3</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">如是的学习博客</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">走进Django</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-11-01T07:01:20.000Z" title="发表于 2022-11-01 15:01:20">2022-11-01</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-11-18T17:18:40.521Z" title="更新于 2022-11-19 01:18:40">2022-11-19</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="走进Django"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="Django是什么"><a href="#Django是什么" class="headerlink" title="Django是什么"></a>Django是什么</h2><p><code>Django</code>是一个由<code>Python</code>编写的一个开放源代码的<code>Web</code>应用框架。<code>Python</code>加<code>Django</code>是快速开发、设计、部署网站的最佳组合。</p>
<p>使用<code>Django</code>，只要很少的代码，<code>Python</code>的程序开发人员就可以轻松地完成一个正式网站所需要的大部分内容，并进一步开发出全功能的<code>Web</code>服务<code>Django</code>本身基于<code>MVC</code>模型，即<code>Model</code>（模型）+<code>View</code>（视图）+ <code>Controller</code>（控制器）设计模式，<code>MVC</code>模式使后续对程序的<code>修改</code>和<code>扩展</code>简化，并且使程序某一部分的<code>重复利用</code>成为可能。</p>
<p><code>MVC</code>优势：</p>
<ul>
<li>低耦合</li>
<li>开发快捷</li>
<li>部署方便</li>
<li>可重用性高</li>
<li>维护成本低</li>
<li>…</li>
</ul>
<h3 id="1-1-1-特点"><a href="#1-1-1-特点" class="headerlink" title="1.1.1 特点"></a>1.1.1 特点</h3><ul>
<li>强大的数据库功能</li>
<li>自带强大的后台功能</li>
<li>优雅的网址</li>
</ul>
<h3 id="1-1-2-MVC与MTV模型"><a href="#1-1-2-MVC与MTV模型" class="headerlink" title="1.1.2 MVC与MTV模型"></a>1.1.2 <code>MVC</code>与<code>MTV</code>模型</h3><h4 id="1-1-2-1-MVC模型"><a href="#1-1-2-1-MVC模型" class="headerlink" title="1.1.2.1 MVC模型"></a>1.1.2.1 <code>MVC</code>模型</h4><p><code>MVC</code>模式（<code>Model–view–controller</code>）是软件工程中的一种<code>软件架构模式</code>，把软件系统分为三个基本部分：<code>模型</code>（Model）、<code>视图</code>（View）和<code>控制器</code>（Controller）。</p>
<p><code>MVC</code>以一种插件式的、松耦合的方式连接在一起。</p>
<ul>
<li><code>模型M</code>：编写程序应有的功能，负责业务对象与数据库的映射，即<code>ORM</code>。</li>
<li><code>视图V</code>： 图形界面，负责与用户的交互(页面)。</li>
<li><code>控制器C</code>：负责转发请求，对请求进行处理。</li>
</ul>
<p>简易图：</p>
<p><img src="/pic/django-pic/ModelViewControllerDiagramZh.png" alt="img"></p>
<p>用户操作流程图：</p>
<p><img src="/pic/django-pic/1589776521-2356-JxrlTyMyPgYnQpOV.png" alt="img"></p>
<h4 id="1-1-2-2-MTV模型"><a href="#1-1-2-2-MTV模型" class="headerlink" title="1.1.2.2 MTV模型"></a>1.1.2.2 <code>MTV</code>模型</h4><p><code>Django</code>的<code>MTV</code>模式本质上和<code>MVC</code>是一样的，也是为了各组件间保持松耦合关系，只是定义上有些许不同，<code>Django</code>的<code>MTV</code>分别是指：</p>
<ul>
<li><code>M</code>表示模型<code>Model</code>：编写程序应有的功能，负责业务对象与数据库的映射，即<code>ORM</code>。</li>
<li><code>T </code>表示模板<code>Template</code>：负责如何把页面<code>html</code>展示给用户。</li>
<li><code>V</code>表示视图<code>View</code>：负责业务逻辑，并在适当时候调用<code>Model</code>和<code>Template</code>。</li>
</ul>
<p>除了以上三层之外，还需要一个<code>URL</code>分发器，它的作用是将一个个<code>URL</code>的页面请求分发给不同的<code>View</code>处理，<code>View</code>再调用相应的 <code>Model</code>和<code>Template</code>，<code>MTV</code>的响应模式如下所示：</p>
<p>简易图：</p>
<p><img src="/pic/django-pic/MTV-Diagram.png" alt="img"></p>
<p>用户操作流程图：</p>
<p><img src="/pic/django-pic/1589777036-2760-fs1oSv4dOWAwC5yW.png" alt="img"></p>
<p><strong>解析：</strong></p>
<p>用户通过浏览器向我们的服务器发起一个<code>request</code>请求，这个请求会去访问视图函数：</p>
<ul>
<li>如果不涉及到数据调用，那么这个时候视图函数直接返回一个模板也就是一个网页给用户。</li>
<li>如果涉及到数据调用，那么视图函数调用模型，模型去数据库查找数据，然后逐级返回。</li>
</ul>
<h2 id="视图函数把返回的数据填充到模板中去，最后返回网页给用户。"><a href="#视图函数把返回的数据填充到模板中去，最后返回网页给用户。" class="headerlink" title="视图函数把返回的数据填充到模板中去，最后返回网页给用户。"></a>视图函数把返回的数据填充到模板中去，最后返回网页给用户。</h2><h2 id="Django发展历程"><a href="#Django发展历程" class="headerlink" title="Django发展历程"></a>Django发展历程</h2><p>目前最新版本4.0 ，Python版本推荐3.6、3.7、3.8</p>
<p>官方文档：<a target="_blank" rel="noopener" href="https://docs.djangoproject.com/zh-hans/3.1/">https://docs.djangoproject.com/zh-hans/3.1/</a></p>
<p><img src="/pic/django-pic/image-20221107204325249.png" alt="image-20221107204325249"></p>
<h2 id="开发环境准备"><a href="#开发环境准备" class="headerlink" title="开发环境准备"></a>开发环境准备</h2><table>
<thead>
<tr>
<th>序号</th>
<th>软件名称</th>
<th>安装方式</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td>Python3.8</td>
<td>官方网站下载安装程序：<a target="_blank" rel="noopener" href="https://www.python.org/downloads/windows/">https://www.python.org/downloads/windows/</a></td>
</tr>
<tr>
<td>2</td>
<td>Django3.0</td>
<td>pip install django&#x3D;&#x3D;3.0.5</td>
</tr>
<tr>
<td>3</td>
<td>PyMySQL</td>
<td>pip install pymysql</td>
</tr>
<tr>
<td>4</td>
<td>MySQL5.7</td>
<td><a target="_blank" rel="noopener" href="https://dev.mysql.com/downloads/mysql/">https://dev.mysql.com/downloads/mysql/</a></td>
</tr>
</tbody></table>
<hr>
<h3 id="安装python"><a href="#安装python" class="headerlink" title="安装python"></a>安装python</h3><p>略。</p>
<h3 id="安装指定版本的Django"><a href="#安装指定版本的Django" class="headerlink" title="安装指定版本的Django"></a>安装指定版本的Django</h3><h4 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h4><p>打开cmd，在cmd中执行Django的安装命令</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">pip install django==<span class="number">3.0</span><span class="number">.5</span></span><br><span class="line"></span><br><span class="line"><span class="comment">## 如果按照较慢的话，可指定按照源</span></span><br><span class="line">pip install -i http://mirrors.aliyun.com/pypi/simple/ django==<span class="number">3.0</span><span class="number">.5</span></span><br></pre></td></tr></table></figure>

<h4 id="检查安装结果"><a href="#检查安装结果" class="headerlink" title="检查安装结果"></a>检查安装结果</h4><ul>
<li>方法1</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">pip <span class="built_in">list</span></span><br><span class="line">Package            Version</span><br><span class="line">------------------ -------</span><br><span class="line">asgiref            <span class="number">3.5</span><span class="number">.2</span></span><br><span class="line">backports.zoneinfo <span class="number">0.2</span><span class="number">.1</span></span><br><span class="line">Django             <span class="number">3.0</span><span class="number">.5</span>        <span class="comment"># 安装成功</span></span><br><span class="line">pip                <span class="number">20.2</span><span class="number">.1</span></span><br><span class="line">pytz               <span class="number">2022.6</span></span><br><span class="line">setuptools         <span class="number">49.2</span><span class="number">.1</span></span><br><span class="line">sqlparse           <span class="number">0.4</span><span class="number">.3</span></span><br><span class="line">tzdata             <span class="number">2022.6</span></span><br></pre></td></tr></table></figure>

<ul>
<li>方法2</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; import django</span><br><span class="line">&gt;&gt;&gt; django.VERSION</span><br><span class="line">(3, 0, 5, &#x27;final&#x27;, 0)</span><br></pre></td></tr></table></figure>

<ul>
<li>方法3</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">C:\Users\rushiy&gt; django-admin version</span><br><span class="line"><span class="number">3.0</span><span class="number">.5</span></span><br><span class="line"></span><br><span class="line">C:\Users\rushiy&gt;django-admin     <span class="comment">## 查看django-admin命令的帮助信息</span></span><br><span class="line"></span><br><span class="line"><span class="type">Type</span> <span class="string">&#x27;django-admin help &lt;subcommand&gt;&#x27;</span> <span class="keyword">for</span> <span class="built_in">help</span> on a specific subcommand.</span><br><span class="line"></span><br><span class="line">Available subcommands:   <span class="comment"># 下面是django-admin的一些命令</span></span><br><span class="line"></span><br><span class="line">[django]</span><br><span class="line">    check</span><br><span class="line">    compilemessages</span><br><span class="line">    createcachetable</span><br><span class="line">    dbshell</span><br><span class="line">    diffsettings</span><br><span class="line">    dumpdata</span><br><span class="line">    flush</span><br><span class="line">    inspectdb</span><br><span class="line">    loaddata</span><br><span class="line">    makemessages</span><br><span class="line">    makemigrations</span><br><span class="line">    migrate</span><br><span class="line">    runserver</span><br><span class="line">    sendtestemail</span><br><span class="line">    shell</span><br><span class="line">    showmigrations</span><br><span class="line">    sqlflush</span><br><span class="line">    sqlmigrate</span><br><span class="line">    sqlsequencereset</span><br><span class="line">    squashmigrations</span><br><span class="line">    startapp</span><br><span class="line">    startproject</span><br><span class="line">    test</span><br><span class="line">    testserver</span><br><span class="line">Note that only Django core commands are listed <span class="keyword">as</span> settings are <span class="keyword">not</span> properly configured (error: Requested setting INSTALLED_APPS, but settings are <span class="keyword">not</span> configured. You must either define the environment variable DJANGO_SETTINGS_MODULE <span class="keyword">or</span> call settings.configure() before accessing settings.).</span><br></pre></td></tr></table></figure>

<p><code>Django</code>的安装目录在python根目录下的<code>\Lib\site-packages</code>中。</p>
<h4 id="Django常用命令"><a href="#Django常用命令" class="headerlink" title="Django常用命令"></a><code>Django</code>常用命令</h4><ul>
<li>检查是否安装<code>django</code>环境：<code>django-admin</code></li>
<li>创建名为<code>myproject</code>的项目：<code>django-admin startproject myproject</code></li>
<li>查看帮助信息：<code>django-admin --help</code></li>
<li>查看<code>Django</code>子命令的帮助信息：<code>django-admin startapp --help </code></li>
<li>创建名为<code>myapp</code>的应用：<code>python manage.py startapp myapp</code></li>
<li>检查项目完整性：<code>python manage.py check</code></li>
<li>本地运行<code>django</code>项目：<code>python manage.py runserver [ip:port]</code></li>
<li>进入<code>django</code>项目的<code>Python shell</code>环境：<code>python manage.py shell　</code></li>
<li>执行<code>django</code>用例测试：<code>python manage.py test　</code></li>
<li>创建模型变更的迁移文件：<code>python manage.py makemigrations</code></li>
<li>执行上一命令创建的迁移文件：<code>python manage.py migrate</code></li>
<li>把数据库数据导出到文件：<code>python manage.py dumpdata</code></li>
<li>把文件数据导入到数据库：<code>python manage.py loaddata</code></li>
</ul>
<h3 id="创建Django项目"><a href="#创建Django项目" class="headerlink" title="创建Django项目"></a>创建Django项目</h3><h4 id="图形化创建Django项目"><a href="#图形化创建Django项目" class="headerlink" title="图形化创建Django项目"></a>图形化创建Django项目</h4><p>以PyCharm为例，打开PyCharm，点击<code>file</code>，选择<code>New Project</code>。</p>
<p><img src="/pic/django-pic/image-20221107205709661.png" alt="image-20221107205709661"></p>
<p>若在新建<code>Django</code>项目之前未安装<code>Django</code>，则<code>PyCharm</code>默认会自动安装最新版<code>Django</code>，若已经安装，会自动跳过该步骤。</p>
<p><img src="/pic/django-pic/image-20221107205425548.png" alt="image-20221107205425548"></p>
<p>新建Django完成后，会自动创建Django的初始文件，如下：</p>
<p><img src="/pic/django-pic/image-20221107205842141.png" alt="image-20221107205842141"></p>
<p>文件说明：</p>
<ul>
<li><code>manager.py</code>：命令行工具文件</li>
<li><code>templates</code>：用来存放<code>html</code>页面，用于展示数据或者内容</li>
<li><code>devops</code>：主文件夹<ul>
<li><code>__init__.py</code>：inti文件，标识当前所在的项目目录是一个Python包，如果在此文件中，通过<code>import</code>导入其他方法或者包会被<code>Django</code>自动识别</li>
<li><code>asgi.py</code>：一个<code>ASGI</code>兼容的<code>Web</code>服务器的入口，以便运行你的项目。</li>
<li><code>urls.py</code>：路由文件，根路由规则文件（应用也可以有该文件）。用于记录<code>Django</code>项目的<code>URL</code>映射关系，它属于项目的基础路由配置文件，路由系统是在这个文件中完成相应配置的，项目中的动态路径必须先经过该文件匹配，才能实现<code>Web</code>站点上资源的访问功能。</li>
<li><code>settings.py</code>：<code>Django</code>整个项目的配置内容文件，项目启动时，<code>settings.py</code>配置文件会被自动调用，而它定义的一些全局为<code>Django</code>运行提供参数，在此配置文件中也可以自定义一些变量，用于全局作用域的数据传递。</li>
<li><code>wsgi.py</code>：<code>WSGI</code>（<code>Web Server Gateway Interface</code>）服务器程序的入口文件，主要用于启动应用程序。它遵守<code>WSGI</code>协议并负责网络通讯部分的实现，只有在项目部署的时候才会用到它。</li>
</ul>
</li>
</ul>
<h4 id="命令行创建Django项目"><a href="#命令行创建Django项目" class="headerlink" title="命令行创建Django项目"></a>命令行创建Django项目</h4><p>打开cmd，在cmd中执行创建Django项目命令</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">django-admin startproject devops</span><br></pre></td></tr></table></figure>

<p>安装完成后，查看的结果如下：</p>
<p><img src="/pic/django-pic/image-20221107211115424.png" alt="image-20221107211115424"></p>
<h3 id="创建和运行应用"><a href="#创建和运行应用" class="headerlink" title="创建和运行应用"></a>创建和运行应用</h3><p>在Django中，<code>项目</code>是指被视为基于某些设置项的Django安装结果；<code>应用程序</code>是指表示为模型、视图、模板、以及URL的组合。应用程序与框架进行交互，提供特定的功能，并可在不同的项目中加以复用。我们可以将项目视为一个站点，其中包含了多个应用程序，例如：博客、wiki或者论坛等，同时还可以被其他项目予以复用。项目和应用的关系如下图所示：</p>
<img src="/pic/django-pic/image-20221107211232219.png" alt="image-20221107211232219" style="zoom: 67%;" />

<h4 id="创建应用"><a href="#创建应用" class="headerlink" title="创建应用"></a>创建应用</h4><p>在项目目录下（<code>manage.py</code>文件的同级目录），执行应用创建命令。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## 方法1</span></span><br><span class="line">python manage.py startapp myapp</span><br><span class="line"></span><br><span class="line"><span class="comment">## 方法2</span></span><br><span class="line">django-admin startapp myapp</span><br></pre></td></tr></table></figure>

<blockquote>
<p>创建应用的方式都是在命令行执行上面的其中一个命令。</p>
<p>在PyCharm中执行该命令时，可能遇到报错，如果提示<code>NameError: name &#39;os&#39; is not defined</code>，则在<code>settings.py</code>文件行首添加一行<code>import os</code>。</p>
</blockquote>
<p>应用创建完成后，项目目录如下所示：</p>
<p><img src="/pic/django-pic/image-20221107213239585.png" alt="image-20221107213239585">应用目录文件如下所示：</p>
<p><img src="/pic/django-pic/image-20221107213315664.png" alt="image-20221107213315664">文件用途如下：</p>
<ul>
<li><code>admin.py</code>：可在该文件中注册模型，并将其纳入至<code>Django</code>管理站点中——使用<code>Django</code>管理站点为可选项。</li>
<li><code>apps.py</code>：该文件中包含了该应用程序（如此处的<code>myapp</code>应用）中的主要配置内容。</li>
<li><code>migrations目录</code>：该目录中包含了应用程序的数据迁移。迁移可使<code>Django</code>跟踪模块变化内容，并相应的同步数据库。</li>
<li><code>models.py</code>：所有的<code>Django</code>应用程序都需要设置该文件，其中包含了应用程序的数据模型；但该文件也可被置空。</li>
<li><code>tests.py</code>：可在该文件中添加应用程序测试。</li>
<li><code>views.py</code>：该文件中包含了应用程序<code>逻辑</code>内容，每个视图接收一个<code>HTTP</code>请求，经处理后返回一个响应结果。</li>
</ul>
<h4 id="运行应用"><a href="#运行应用" class="headerlink" title="运行应用"></a>运行应用</h4><p>（1）命令行界面运行应用</p>
<p>在项目根目录下（<code>manage.py</code>文件的同级目录），执行应用运行命令。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">python manage.py runserver <span class="number">0.0</span><span class="number">.0</span><span class="number">.0</span>:<span class="number">8888</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>IP和端口为可选项，默认IP为<code>127.0.0.1</code>，默认端口为<code>8000</code></p>
</blockquote>
<p>此时，可通过浏览器打开。</p>
<p><img src="/pic/django-pic/image-20221107213756530.png" alt="image-20221107213756530"></p>
<p>（2）图形化界面运行运行应用</p>
<p>在PyCharm图形化界面中，点击右上角的运行按钮，即可运行应用。</p>
<p><img src="/pic/django-pic/image-20221107214443442.png" alt="image-20221107214443442"></p>
<blockquote>
<p>更改端口，可点击右上角运行按钮旁边的<code>devops</code>下拉框，点击<code>Edit Configuartions</code>，修改<code>Port</code>即可</p>
</blockquote>
<hr>
<h2 id="牛刀小试"><a href="#牛刀小试" class="headerlink" title="牛刀小试"></a>牛刀小试</h2><p>浏览器访问Django项目的流程如下所示：</p>
<p><img src="/pic/django-pic/image-20221107220458647.png" alt="image-20221107220458647"></p>
<h3 id="第一个网页"><a href="#第一个网页" class="headerlink" title="第一个网页"></a>第一个网页</h3><h4 id="添加URL路由"><a href="#添加URL路由" class="headerlink" title="添加URL路由"></a>添加URL路由</h4><p>指明从浏览器请求的<code>url</code>去找哪个文件响应</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># devops/urls.py</span></span><br><span class="line"><span class="keyword">from</span> django.contrib <span class="keyword">import</span> admin</span><br><span class="line"><span class="keyword">from</span> django.urls <span class="keyword">import</span> path </span><br><span class="line"><span class="keyword">from</span> myapp <span class="keyword">import</span> views           <span class="comment"># 从myapp包中导入views模块</span></span><br><span class="line"></span><br><span class="line">urlpatterns = [</span><br><span class="line">    path(<span class="string">&#x27;index&#x27;</span>, views.index),       <span class="comment"># 当浏览器请求的路径是index时，去找views.py文件中的index函数</span></span><br><span class="line"><span class="comment">#    path(&#x27;admin/&#x27;, admin.site.urls),  # Django的默认首页，可注释或删除改行内容</span></span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<h4 id="添加视图"><a href="#添加视图" class="headerlink" title="添加视图"></a>添加视图</h4><blockquote>
<p>在应用目录<code>myapp</code>中的<code>views.py</code>文件。</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># myapp/views.py</span></span><br><span class="line"><span class="keyword">from</span> django.shortcuts <span class="keyword">import</span> render, HttpResponse</span><br><span class="line"></span><br><span class="line"><span class="comment"># Create your views here.</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">index</span>(<span class="params">request</span>):                <span class="comment"># 创建一个index函数，返回一个字符串</span></span><br><span class="line">    <span class="keyword">return</span> HttpResponse(<span class="string">&quot;&lt;center&gt;&lt;h1&gt;网址首页&lt;/h1&gt;&lt;/center&gt;&quot;</span>)</span><br></pre></td></tr></table></figure>

<h4 id="浏览器访问"><a href="#浏览器访问" class="headerlink" title="浏览器访问"></a>浏览器访问</h4><p>点击PyCharm右上角的<code>运行</code>按钮运行应用。</p>
<blockquote>
<p>接下来的项目运行均通过PyCharm图形化界面运行</p>
</blockquote>
<p><img src="/pic/django-pic/image-20221107221650084.png" alt="image-20221107221650084"></p>
<h3 id="案例"><a href="#案例" class="headerlink" title="案例"></a>案例</h3><p>案例功能：网页展示日志文件。此案例中的文件路径如下：</p>
<img src="/pic/django-pic/image-20221107232438049.png" alt="image-20221107232438049" style="zoom:67%;" />

<h4 id="创建html模板和日志文件"><a href="#创建html模板和日志文件" class="headerlink" title="创建html模板和日志文件"></a>创建html模板和日志文件</h4><ul>
<li>html模板</li>
</ul>
<p>在项目根目录下的<code>templates</code>目录下，新建<code>logs.html</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=<span class="string">&quot;en&quot;</span>&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">    &lt;meta charset=<span class="string">&quot;UTF-8&quot;</span>&gt;</span><br><span class="line">    &lt;title&gt;日志展示&lt;/title&gt;</span><br><span class="line">&lt;/head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">&lt;h1&gt;Nginx访问日志&lt;/h1&gt;</span><br><span class="line">&lt;div style=<span class="string">&quot;background-color: black;color: white&quot;</span>&gt;</span><br><span class="line">    &lt;span style=<span class="string">&quot;font-size: 18px&quot;</span>&gt;&lt;pre&gt;&#123;&#123; result &#125;&#125;&lt;/pre&gt;&lt;/span&gt;</span><br><span class="line">&lt;/div&gt;</span><br><span class="line"></span><br><span class="line">&lt;/body&gt;</span><br><span class="line">&lt;/html&gt;</span><br></pre></td></tr></table></figure>

<p><code>Django</code>中的<code>html</code>文件是模板，<code>html</code>文件并没有写实际的静态页面内容，而是将<code>Django</code>的处理结果传递给<code>html</code>模板，然后展示在浏览器中。<code>html</code>中的<code>result</code>即是<code>views.py</code>文件传递给<code>logs.html</code>的。即：业务逻辑是在<code>py</code>文件中实现的，<code>html</code>接收<code>py</code>文件的处理结果，将结果按照<code>html</code>文件的定义展示出来。</p>
<ul>
<li>日志文件</li>
</ul>
<p>在项目根目录下新建<code>access.log</code>文件，文件内容如下：</p>
<figure class="highlight tex"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">178.174.137.125 - - [30/Oct/2021:07:46:28 +0800] &quot;GET / HTTP/1.0&quot; 200 612 &quot;-&quot; &quot;-&quot;</span><br><span class="line">206.221.176.148 - - [30/Oct/2021:07:59:33 +0800] &quot;GET http://1.1.1.1/cdn-cgi/trace HTTP/1.1&quot; 404 152 &quot;-&quot; &quot;Go-http-client/1.1&quot;</span><br><span class="line">81.163.45.248 - - [30/Oct/2021:08:24:22 +0800] &quot;GET / HTTP/1.1&quot; 200 612 &quot;-&quot; &quot;Mozilla/5.0 (Macintosh; Intel Mac OS X 10<span class="built_in">_</span>11<span class="built_in">_</span>6) AppleWebKit/601.7.7 (KHTML, like Gecko) Version/9.1.2 Safari/601.7.7&quot;</span><br><span class="line">106.52.34.90 - - [30/Oct/2021:08:29:13 +0800] &quot;GET / HTTP/1.1&quot; 200 396 &quot;-&quot; &quot;Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)&quot;</span><br><span class="line">209.141.51.171 - - [30/Oct/2021:08:44:30 +0800] &quot;POST /boaform/admin/formLogin HTTP/1.1&quot; 404 152 &quot;http://82.156.236.147:80/admin/login.asp&quot; &quot;Mozilla/5.0 (X11; Ubuntu; Linux x86<span class="built_in">_</span>64; rv:71.0) Gecko/20100101 Firefox/71.0&quot;</span><br><span class="line">209.141.51.171 - - [30/Oct/2021:08:44:31 +0800] &quot;&quot; 400 0 &quot;-&quot; &quot;-&quot;</span><br><span class="line">165.227.136.172 - - [30/Oct/2021:09:01:41 +0800] &quot;GET / HTTP/1.0&quot; 200 612 &quot;-&quot; &quot;-&quot;</span><br><span class="line">128.14.133.58 - - [30/Oct/2021:09:29:23 +0800] &quot;GET / HTTP/1.1&quot; 200 396 &quot;-&quot; &quot;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36&quot;</span><br><span class="line">20.115.67.160 - - [30/Oct/2021:09:41:21 +0800] &quot;HEAD /robots.txt HTTP/1.0&quot; 404 0 &quot;-&quot; &quot;-&quot;</span><br><span class="line">205.185.120.103 - - [30/Oct/2021:09:43:28 +0800] &quot;GET / HTTP/1.1&quot; 200 396 &quot;-&quot; &quot;Linux Gnu (cow)&quot;</span><br><span class="line">178.174.137.125 - - [30/Oct/2021:07:46:28 +0800] &quot;GET / HTTP/1.0&quot; 200 612 &quot;-&quot; &quot;-&quot;</span><br><span class="line">206.221.176.148 - - [30/Oct/2021:07:59:33 +0800] &quot;GET http://1.1.1.1/cdn-cgi/trace HTTP/1.1&quot; 404 152 &quot;-&quot; &quot;Go-http-client/1.1&quot;</span><br><span class="line">81.163.45.248 - - [30/Oct/2021:08:24:22 +0800] &quot;GET / HTTP/1.1&quot; 200 612 &quot;-&quot; &quot;Mozilla/5.0 (Macintosh; Intel Mac OS X 10<span class="built_in">_</span>11<span class="built_in">_</span>6) AppleWebKit/601.7.7 (KHTML, like Gecko) Version/9.1.2 Safari/601.7.7&quot;</span><br><span class="line">106.52.34.90 - - [30/Oct/2021:08:29:13 +0800] &quot;GET / HTTP/1.1&quot; 200 396 &quot;-&quot; &quot;Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)&quot;</span><br><span class="line">209.141.51.171 - - [30/Oct/2021:08:44:30 +0800] &quot;POST /boaform/admin/formLogin HTTP/1.1&quot; 404 152 &quot;http://82.156.236.147:80/admin/login.asp&quot; &quot;Mozilla/5.0 (X11; Ubuntu; Linux x86<span class="built_in">_</span>64; rv:71.0) Gecko/20100101 Firefox/71.0&quot;</span><br><span class="line">209.141.51.171 - - [30/Oct/2021:08:44:31 +0800] &quot;&quot; 400 0 &quot;-&quot; &quot;-&quot;</span><br><span class="line">165.227.136.172 - - [30/Oct/2021:09:01:41 +0800] &quot;GET / HTTP/1.0&quot; 200 612 &quot;-&quot; &quot;-&quot;</span><br><span class="line">128.14.133.58 - - [30/Oct/2021:09:29:23 +0800] &quot;GET / HTTP/1.1&quot; 200 396 &quot;-&quot; &quot;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36&quot;</span><br><span class="line">20.115.67.160 - - [30/Oct/2021:09:41:21 +0800] &quot;HEAD /robots.txt HTTP/1.0&quot; 404 0 &quot;-&quot; &quot;-&quot;</span><br><span class="line">205.185.120.103 - - [30/Oct/2021:09:43:28 +0800] &quot;GET / HTTP/1.1&quot; 200 396 &quot;-&quot; &quot;Linux Gnu (cow)&quot;</span><br><span class="line">178.174.137.125 - - [30/Oct/2021:07:46:28 +0800] &quot;GET / HTTP/1.0&quot; 200 612 &quot;-&quot; &quot;-&quot;</span><br><span class="line">206.221.176.148 - - [30/Oct/2021:07:59:33 +0800] &quot;GET http://1.1.1.1/cdn-cgi/trace HTTP/1.1&quot; 404 152 &quot;-&quot; &quot;Go-http-client/1.1&quot;</span><br><span class="line">81.163.45.248 - - [30/Oct/2021:08:24:22 +0800] &quot;GET / HTTP/1.1&quot; 200 612 &quot;-&quot; &quot;Mozilla/5.0 (Macintosh; Intel Mac OS X 10<span class="built_in">_</span>11<span class="built_in">_</span>6) AppleWebKit/601.7.7 (KHTML, like Gecko) Version/9.1.2 Safari/601.7.7&quot;</span><br><span class="line">106.52.34.90 - - [30/Oct/2021:08:29:13 +0800] &quot;GET / HTTP/1.1&quot; 200 396 &quot;-&quot; &quot;Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)&quot;</span><br><span class="line">209.141.51.171 - - [30/Oct/2021:08:44:30 +0800] &quot;POST /boaform/admin/formLogin HTTP/1.1&quot; 404 152 &quot;http://82.156.236.147:80/admin/login.asp&quot; &quot;Mozilla/5.0 (X11; Ubuntu; Linux x86<span class="built_in">_</span>64; rv:71.0) Gecko/20100101 Firefox/71.0&quot;</span><br><span class="line">209.141.51.171 - - [30/Oct/2021:08:44:31 +0800] &quot;&quot; 400 0 &quot;-&quot; &quot;-&quot;</span><br><span class="line">165.227.136.172 - - [30/Oct/2021:09:01:41 +0800] &quot;GET / HTTP/1.0&quot; 200 612 &quot;-&quot; &quot;-&quot;</span><br><span class="line">128.14.133.58 - - [30/Oct/2021:09:29:23 +0800] &quot;GET / HTTP/1.1&quot; 200 396 &quot;-&quot; &quot;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36&quot;</span><br><span class="line">20.115.67.160 - - [30/Oct/2021:09:41:21 +0800] &quot;HEAD /robots.txt HTTP/1.0&quot; 404 0 &quot;-&quot; &quot;-&quot;</span><br><span class="line">205.185.120.103 - - [30/Oct/2021:09:43:28 +0800] &quot;GET / HTTP/1.1&quot; 200 396 &quot;-&quot; &quot;Linux Gnu (cow)&quot;</span><br></pre></td></tr></table></figure>

<h4 id="添加url路由"><a href="#添加url路由" class="headerlink" title="添加url路由"></a>添加url路由</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># devops/urls.py</span></span><br><span class="line"><span class="keyword">from</span> django.contrib <span class="keyword">import</span> admin</span><br><span class="line"><span class="keyword">from</span> django.urls <span class="keyword">import</span> path </span><br><span class="line"><span class="keyword">from</span> myapp <span class="keyword">import</span> views</span><br><span class="line"></span><br><span class="line">urlpatterns = [</span><br><span class="line">    path(<span class="string">&#x27;index&#x27;</span>, views.index), </span><br><span class="line">    path(<span class="string">&#x27;logs&#x27;</span>, views.logs),    <span class="comment"># 此处的views.logs中的views表示views.py文件，logs表示该文件中的logs函数</span></span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<h4 id="添加视图-1"><a href="#添加视图-1" class="headerlink" title="添加视图"></a>添加视图</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># myapp/views.py</span></span><br><span class="line"><span class="keyword">from</span> django.shortcuts <span class="keyword">import</span> render</span><br><span class="line"><span class="keyword">from</span> django.http <span class="keyword">import</span> HttpResponse </span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">index</span>(<span class="params">request</span>):</span><br><span class="line">    <span class="keyword">return</span> HttpResponse(<span class="string">&quot;&lt;center&gt;&lt;h1&gt;网址首页&lt;/h1&gt;&lt;/center&gt;&quot;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">logs</span>(<span class="params">request</span>):       <span class="comment"># 此处的函数名logs跟urls.py文件中的views.logs</span></span><br><span class="line">    <span class="keyword">import</span> os</span><br><span class="line"></span><br><span class="line">    current_dir = os.path.dirname(os.path.abspath(__file__)).split(<span class="string">&quot;\\&quot;</span>)  <span class="comment"># 将路径以反斜线分割</span></span><br><span class="line">    current_dir.pop()  <span class="comment"># 去掉列表中的最后一个元素</span></span><br><span class="line">    current_dir = <span class="string">&quot;\\&quot;</span>.join(current_dir)  <span class="comment"># 将列表中的元素以反斜线连接起来</span></span><br><span class="line">    <span class="built_in">print</span>(current_dir + <span class="string">&#x27;\\access.log&#x27;</span>)</span><br><span class="line">    <span class="keyword">with</span> <span class="built_in">open</span>(current_dir + <span class="string">&#x27;\\access.log&#x27;</span>) <span class="keyword">as</span> f:</span><br><span class="line">        result = f.read()</span><br><span class="line">    <span class="keyword">return</span> render(request, <span class="string">&quot;logs.html&quot;</span>, &#123;<span class="string">&quot;result&quot;</span>: result&#125;)</span><br></pre></td></tr></table></figure>

<p>注意：变量<code>current_dir</code>的三行内容是为了获取到<code>access.log</code>的路径，因为<code>access.log</code>文件与<code>myapp</code>应用同层级，因此在<code>myapp/views.py</code>文件的上一个目录，所以需要修改将获取到的第一个<code>current_dir变量中的</code>myapp&#96;去掉。</p>
<h4 id="浏览器访问-1"><a href="#浏览器访问-1" class="headerlink" title="浏览器访问"></a>浏览器访问</h4><h2 id=""><a href="#" class="headerlink" title=""></a><img src="/pic/django-pic/image-20221107231909732.png" alt="image-20221107231909732"></h2><h2 id="Django工作流程"><a href="#Django工作流程" class="headerlink" title="Django工作流程"></a>Django工作流程</h2><h3 id="简单工作流程"><a href="#简单工作流程" class="headerlink" title="简单工作流程"></a>简单工作流程</h3><p>通过上面的案例，我们可以简单剖析一下Django的工作流程。</p>
<p><img src="/pic/django-pic/image-20221107233610393.png" alt="image-20221107233610393"></p>
<p>如上图所示：</p>
<ul>
<li><p>用户在客户端浏览器输入<code>URL地址</code>，通过<code>get</code>或<code>post</code>请求方式，向服务端发起请求；</p>
</li>
<li><p><code>Django</code>服务端接收到客户端请求，通过<code>urls.py</code>中地址与处理函数之间的一一对应，找到对应的视图函数；</p>
</li>
<li><p>开始执行对应视图函数中的逻辑；</p>
</li>
<li><p>与<code>templates</code>交互，将参数返回到前端页面，并通过<code>templates</code>进行<code>html</code>页面渲染。</p>
</li>
</ul>
<h3 id="完整工作流程"><a href="#完整工作流程" class="headerlink" title="完整工作流程"></a>完整工作流程</h3><p>上面是一个最简单的<code>Django</code>工作流程。下面是<code>Django</code>完整的工作流程。</p>
<p><code>django</code>工作模式是<code>MTV</code>模式，其中M代表模型<code>model</code>，T代表模块<code>template</code>，V代表视图<code>view</code></p>
<ul>
<li><code>M</code>：负责业务对象和数据库的关系映射；</li>
<li><code>T</code>：负责如何把页面展示给用户；</li>
<li><code>V</code>：负责业务逻辑，并在适当的时候调用<code>Model</code>和<code>Template</code>；</li>
</ul>
<p>此外，<code>Django</code>还有一个<code>url</code>分发器，它的作用是将一个个<code>URL</code>的页面请求分发给不同的<code>view</code>处理，<code>view</code>再调用相应的<code>Model</code>和<code>Template</code>。</p>
<p><code>Django</code>具体工作流程如下：</p>
<p><img src="/pic/django-pic/image-20221107234319396.png" alt="image-20221107234319396"></p>
<ol>
<li><code> 接收web请求</code>，浏览器通过<code> socket</code> 发送请求，由<code> wsgi.py</code> 完成接收，按<code> http协议</code> 解析为<code> request对象</code> ；</li>
<li><code> 中间件处理</code>  ，<code> ruquest对象</code> 按顺序执行中间件的方法传到<code> url控制器</code> ；</li>
<li><code> 将url请求分配给view模块</code>  ，<code> url控制器</code> 可通过<code> 正则</code> 匹配请求的路径，将请求分配给不同的<code> view模块</code> ；</li>
<li><code> view函数</code>  ，视图函数根据请求内容，调用模块（<code> templat</code>e<code> ）中相应的</code> html<code> 页面；此外，</code> view函数&#96; 可以与数据库进行交互。</li>
<li><code> 将html文件传输给浏览器</code> ，<code> view函数</code> 执行后返回的<code> html文件</code> 经过中间件方法处理，再在<code> wsgi.py函数</code> 中按<code> http协议</code> 封装为响应数据；</li>
</ol>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://rushiy.gitee.io">rushiy</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://rushiy.gitee.io/django/%E8%B5%B0%E8%BF%9BDjango/">https://rushiy.gitee.io/django/%E8%B5%B0%E8%BF%9BDjango/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://rushiy.gitee.io" target="_blank">如是的学习博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/django/">django</a></div><div class="post_share"><div class="social-share" data-image="" data-sites="wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/favicon.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">rushiy</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">28</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">3</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><div class="card-info-social-icons is-center"><a class="social-icon" href="mailto:rushiy@reg.email.cn" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Django%E6%98%AF%E4%BB%80%E4%B9%88"><span class="toc-number">1.</span> <span class="toc-text">Django是什么</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-1-%E7%89%B9%E7%82%B9"><span class="toc-number">1.1.</span> <span class="toc-text">1.1.1 特点</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-2-MVC%E4%B8%8EMTV%E6%A8%A1%E5%9E%8B"><span class="toc-number">1.2.</span> <span class="toc-text">1.1.2 MVC与MTV模型</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-1-2-1-MVC%E6%A8%A1%E5%9E%8B"><span class="toc-number">1.2.1.</span> <span class="toc-text">1.1.2.1 MVC模型</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-1-2-2-MTV%E6%A8%A1%E5%9E%8B"><span class="toc-number">1.2.2.</span> <span class="toc-text">1.1.2.2 MTV模型</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%A7%86%E5%9B%BE%E5%87%BD%E6%95%B0%E6%8A%8A%E8%BF%94%E5%9B%9E%E7%9A%84%E6%95%B0%E6%8D%AE%E5%A1%AB%E5%85%85%E5%88%B0%E6%A8%A1%E6%9D%BF%E4%B8%AD%E5%8E%BB%EF%BC%8C%E6%9C%80%E5%90%8E%E8%BF%94%E5%9B%9E%E7%BD%91%E9%A1%B5%E7%BB%99%E7%94%A8%E6%88%B7%E3%80%82"><span class="toc-number">2.</span> <span class="toc-text">视图函数把返回的数据填充到模板中去，最后返回网页给用户。</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Django%E5%8F%91%E5%B1%95%E5%8E%86%E7%A8%8B"><span class="toc-number">3.</span> <span class="toc-text">Django发展历程</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%BC%80%E5%8F%91%E7%8E%AF%E5%A2%83%E5%87%86%E5%A4%87"><span class="toc-number">4.</span> <span class="toc-text">开发环境准备</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%89%E8%A3%85python"><span class="toc-number">4.1.</span> <span class="toc-text">安装python</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%89%E8%A3%85%E6%8C%87%E5%AE%9A%E7%89%88%E6%9C%AC%E7%9A%84Django"><span class="toc-number">4.2.</span> <span class="toc-text">安装指定版本的Django</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AE%89%E8%A3%85"><span class="toc-number">4.2.1.</span> <span class="toc-text">安装</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%A3%80%E6%9F%A5%E5%AE%89%E8%A3%85%E7%BB%93%E6%9E%9C"><span class="toc-number">4.2.2.</span> <span class="toc-text">检查安装结果</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Django%E5%B8%B8%E7%94%A8%E5%91%BD%E4%BB%A4"><span class="toc-number">4.2.3.</span> <span class="toc-text">Django常用命令</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%9B%E5%BB%BADjango%E9%A1%B9%E7%9B%AE"><span class="toc-number">4.3.</span> <span class="toc-text">创建Django项目</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%9B%BE%E5%BD%A2%E5%8C%96%E5%88%9B%E5%BB%BADjango%E9%A1%B9%E7%9B%AE"><span class="toc-number">4.3.1.</span> <span class="toc-text">图形化创建Django项目</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%91%BD%E4%BB%A4%E8%A1%8C%E5%88%9B%E5%BB%BADjango%E9%A1%B9%E7%9B%AE"><span class="toc-number">4.3.2.</span> <span class="toc-text">命令行创建Django项目</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E5%92%8C%E8%BF%90%E8%A1%8C%E5%BA%94%E7%94%A8"><span class="toc-number">4.4.</span> <span class="toc-text">创建和运行应用</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E5%BA%94%E7%94%A8"><span class="toc-number">4.4.1.</span> <span class="toc-text">创建应用</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%BF%90%E8%A1%8C%E5%BA%94%E7%94%A8"><span class="toc-number">4.4.2.</span> <span class="toc-text">运行应用</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%89%9B%E5%88%80%E5%B0%8F%E8%AF%95"><span class="toc-number">5.</span> <span class="toc-text">牛刀小试</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%AC%AC%E4%B8%80%E4%B8%AA%E7%BD%91%E9%A1%B5"><span class="toc-number">5.1.</span> <span class="toc-text">第一个网页</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B7%BB%E5%8A%A0URL%E8%B7%AF%E7%94%B1"><span class="toc-number">5.1.1.</span> <span class="toc-text">添加URL路由</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B7%BB%E5%8A%A0%E8%A7%86%E5%9B%BE"><span class="toc-number">5.1.2.</span> <span class="toc-text">添加视图</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B5%8F%E8%A7%88%E5%99%A8%E8%AE%BF%E9%97%AE"><span class="toc-number">5.1.3.</span> <span class="toc-text">浏览器访问</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A1%88%E4%BE%8B"><span class="toc-number">5.2.</span> <span class="toc-text">案例</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%9B%E5%BB%BAhtml%E6%A8%A1%E6%9D%BF%E5%92%8C%E6%97%A5%E5%BF%97%E6%96%87%E4%BB%B6"><span class="toc-number">5.2.1.</span> <span class="toc-text">创建html模板和日志文件</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B7%BB%E5%8A%A0url%E8%B7%AF%E7%94%B1"><span class="toc-number">5.2.2.</span> <span class="toc-text">添加url路由</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B7%BB%E5%8A%A0%E8%A7%86%E5%9B%BE-1"><span class="toc-number">5.2.3.</span> <span class="toc-text">添加视图</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B5%8F%E8%A7%88%E5%99%A8%E8%AE%BF%E9%97%AE-1"><span class="toc-number">5.2.4.</span> <span class="toc-text">浏览器访问</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">6.</span> <span class="toc-text"></span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Django%E5%B7%A5%E4%BD%9C%E6%B5%81%E7%A8%8B"><span class="toc-number">7.</span> <span class="toc-text">Django工作流程</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%AE%80%E5%8D%95%E5%B7%A5%E4%BD%9C%E6%B5%81%E7%A8%8B"><span class="toc-number">7.1.</span> <span class="toc-text">简单工作流程</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%8C%E6%95%B4%E5%B7%A5%E4%BD%9C%E6%B5%81%E7%A8%8B"><span class="toc-number">7.2.</span> <span class="toc-text">完整工作流程</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/django/Django%E6%A8%A1%E6%9D%BF%E7%B3%BB%E7%BB%9F/" title="Django模板系统"><img src="" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Django模板系统"/></a><div class="content"><a class="title" href="/django/Django%E6%A8%A1%E6%9D%BF%E7%B3%BB%E7%BB%9F/" title="Django模板系统">Django模板系统</a><time datetime="2022-11-04T07:08:03.000Z" title="发表于 2022-11-04 15:08:03">2022-11-04</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/django/Django%E8%A7%86%E5%9B%BE/" title="Django视图"><img src="" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Django视图"/></a><div class="content"><a class="title" href="/django/Django%E8%A7%86%E5%9B%BE/" title="Django视图">Django视图</a><time datetime="2022-11-03T07:07:51.000Z" title="发表于 2022-11-03 15:07:51">2022-11-03</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/django/Django%E8%B7%AF%E7%94%B1%E7%B3%BB%E7%BB%9F/" title="Django路由系统"><img src="" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Django路由系统"/></a><div class="content"><a class="title" href="/django/Django%E8%B7%AF%E7%94%B1%E7%B3%BB%E7%BB%9F/" title="Django路由系统">Django路由系统</a><time datetime="2022-11-02T07:07:34.000Z" title="发表于 2022-11-02 15:07:34">2022-11-02</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/django/%E8%B5%B0%E8%BF%9BDjango/" title="走进Django"><img src="" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="走进Django"/></a><div class="content"><a class="title" href="/django/%E8%B5%B0%E8%BF%9BDjango/" title="走进Django">走进Django</a><time datetime="2022-11-01T07:01:20.000Z" title="发表于 2022-11-01 15:01:20">2022-11-01</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/python/python%E5%B8%B8%E7%94%A8%E6%A8%A1%E5%9D%97/" title="python常用模块"><img src="" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="python常用模块"/></a><div class="content"><a class="title" href="/python/python%E5%B8%B8%E7%94%A8%E6%A8%A1%E5%9D%97/" title="python常用模块">python常用模块</a><time datetime="2022-10-28T15:34:07.000Z" title="发表于 2022-10-28 23:34:07">2022-10-28</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2022 By rushiy</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><div class="js-pjax"></div><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>